package com.qianjing.project.system.controller;

import cn.gov.customs.casp.sdk.h4a.AccreditBeanReaderHelper;
import cn.gov.customs.casp.sdk.h4a.OguBeanReaderHelper;
import cn.gov.customs.casp.sdk.h4a.accredit.ws.*;
import cn.gov.customs.casp.sdk.h4a.entity.*;
import cn.gov.customs.casp.sdk.h4a.enumdefines.*;
import cn.gov.customs.casp.sdk.h4a.ogu.ws.IOguReaderGetObjectsDetailCupaaFaultArgsFaultFaultMessage;
import cn.gov.customs.casp.sdk.h4a.ogu.ws.ObjectCategory;
import cn.gov.customs.casp.sdk.h4a.sso.passport.Ticket;
import cn.gov.customs.casp.sdk.h4a.sso.passport.util.PassportManager;
import com.qianjing.common.constant.Constants;
import com.qianjing.common.constant.UserConstants;
import com.qianjing.common.utils.SecurityUtils;
import com.qianjing.common.utils.IdUtils;
import com.qianjing.framework.security.LoginBody;
import com.qianjing.framework.security.LoginTicket;
import com.qianjing.framework.security.service.SysLoginService;
import com.qianjing.framework.security.service.SysPermissionService;
import com.qianjing.framework.web.domain.AjaxResult;
import com.qianjing.project.system.domain.SysMenu;
import com.qianjing.project.system.domain.SysRole;
import com.qianjing.project.system.domain.SysUser;
import com.qianjing.project.system.service.ISysMenuService;
import com.qianjing.project.system.service.ISysRoleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 登录验证
 *
 * @author qianjing
 */
@RestController
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    private static final Logger log = LoggerFactory.getLogger(SysLoginController.class);

    public static final String paramT = "token";

    private static final String appValue = "SPJY";

    private static final String viewValue = "CCIC_VIEW";


    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody,HttpServletRequest request,HttpServletResponse response)
    {
        AjaxResult ajax = AjaxResult.success();

        // H4A模拟登录
        HttpSession session = request.getSession(true);
        Ticket ticket = new Ticket();
        ticket.setSid(session.getId());
        ticket.setLn(loginBody.getUsername());
        Date date = new Date();
        SimpleDateFormat format=new SimpleDateFormat("yyyyMMddHHmmss");
        String currentTime = format.format(date);
        ticket.setSit(currentTime);
        PassportManager.login(ticket,request,response,"36000");
        String paramToken = IdUtils.simpleUUID();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid(), paramToken);
        ajax.put(Constants.TOKEN, token);
        // H4A回调成功的token
        ajax.put("paramToken", Constants.LOGIN_TOKEN_KEY + paramToken);
        return ajax;
    }

    @GetMapping("/ssoLogin")
    public AjaxResult ssoLogin(HttpServletRequest request, HttpServletResponse response) throws IAccreditReaderGetRolesCupaaFaultArgsFaultFaultMessage, IAccreditReaderGetRolesOfUserCupaaFaultArgsFaultFaultMessage, IOException, IAccreditReaderGetApplicationsByUserCupaaFaultArgsFaultFaultMessage, IOguReaderGetObjectsDetailCupaaFaultArgsFaultFaultMessage, IAccreditReaderGetFunctionsOfUserCupaaFaultArgsFaultFaultMessage, IAccreditReaderGetFunctionsInRolesCupaaFaultArgsFaultFaultMessage {
        HttpSession session = request.getSession(true);
        Boolean isLogin = PassportManager.isLogin(request, response);
        AjaxResult ajax = AjaxResult.success();
        Ticket ticket;
        //String userValue = "sh\\guyu&windows";
        String userValue = "";
        LoginTicket loginTicket = new LoginTicket();
        if (isLogin) {
            ticket = PassportManager.getTicket(request, response);
            log.error("ticket:" + ticket);
            log.error("ticket:" + ticket.getAbm());
            log.error("ticket:" + ticket.getIabm());//认证方式
            log.error("ticket:" + ticket.getIp());  //当前登录的IP地址信息
            log.error("ticket:" + ticket.getLn());  //登陆帐号
            log.error("ticket:" + ticket.getMlm()); //鉴权方式
            log.error("ticket:" + ticket.getSid()); //session编号
            log.error("ticket:" + ticket.getSit());
            log.error("ticket:" + ticket.getLn());
            log.info("-----------------------h4A登录成功-------------------------");
            log.info("登录账号+++++++++++++++++++++：" +ticket.getLn());
            log.info("唯一编号+++++++++++++++++++++：" +ticket.getSid());
            if (session.getAttribute("TICKET") != null) {
                Ticket sessionTicket;
                sessionTicket = (Ticket)session.getAttribute("TICKET");
                System.out.println("从session中获取到的sessionTicket:" + sessionTicket);
                System.out.println("sessionTicket:" + sessionTicket.getAbm());
                System.out.println("sessionTicket:" + sessionTicket.getIabm());//认证方式
                System.out.println("sessionTicket:" + sessionTicket.getIp());  //当前登录的IP地址信息
                System.out.println("sessionTicket:" + sessionTicket.getLn());  //登陆帐号
                System.out.println("sessionTicket:" + sessionTicket.getMlm()); //鉴权方式
                System.out.println("sessionTicket:" + sessionTicket.getSid()); //用户guid
                System.out.println("sessionTicket:" + sessionTicket.getSit());
            }
            String loginName = ticket.getLn();
            log.info("loginName:{}", ticket.getLn());
            // userValue=loginName+"&forms";
            if ((loginName.startsWith("22")) && (loginName.endsWith("0"))) {
                userValue = loginName + "&hrcode";
            } else if (loginName.contains("sh\\")) {
                userValue = loginName + "&windows";
            } else if (!loginName.contains("sh\\")) {
                userValue = "sh\\" + loginName + "&windows";
            }
            log.info("userValue====:{}", userValue);
            loginTicket.setUserName(userValue.trim());
            loginTicket.setIp(ticket.getIp());
        }
        AccreditBeanReaderHelper accreditBeanReaderHelper = new AccreditBeanReaderHelper();
        OguBeanReaderHelper oguBeanReaderHelper = new OguBeanReaderHelper();
        Application[] returnObject = accreditBeanReaderHelper.getBeanApplicationsByUser
                (userValue, UserCategory.USER_IDENTITY, "",
                        OrganizationCategory.NONE,viewValue,
                        AccreditCategory.Code,
                        DelegationCategories.All, "");
        for (Application r : returnObject) {
            System.out.println(r.getSort_id());
            System.out.println(r.getElement_node_result());
            System.out.println("拥有的系统权限="+r.getApplication_name());//拥有的系统权限
        }
        // 获取当前登录用户详细信息
        ObjectsDetail[] userDetails =  oguBeanReaderHelper.getBeanObjectsDetail(viewValue, ViewCategory.ViewCode,
                userValue, ObjectCategory.USER_IDENTITY,"",cn.gov.customs.casp.sdk.h4a.ogu.ws.OrganizationCategory.NONE,"RANK_NAME,RANK_CODE,PERSON_ID");
        if ((userDetails != null) && (userDetails.length > 0)) {
            ObjectsDetail objectsDetail = userDetails[0];
            log.info("getRank_code====:{}", objectsDetail.getRank_code());
            log.info("工号：=============={}", userDetails[0].getPerson_id());
            System.out.println("&&&&&&&&&&&&&&&&");
            System.out.println(objectsDetail.getView_guid());//e1111111-1111-1111-1111-111111111111
            System.out.println(objectsDetail.getUser_guid());  //c6a982bb-26d4-49aa-8911-5678390c1964
            System.out.println(objectsDetail.getParent_guid());//051be6e0-98fa-44d0-bbe5-1f46c76e66e6
            System.out.println(objectsDetail.getObj_name());
            System.out.println(objectsDetail.getAll_path_name());//海关总署\上海海关\技术处\软件一科\谷宇
            System.out.println(objectsDetail.getAttributes());
            System.out.println(objectsDetail.getRank_code());//职务代码  10
            System.out.println(objectsDetail.getRank_name());//职务名称   副主任科员
            System.out.println(objectsDetail.getCustoms_code());
            System.out.println(objectsDetail.getDisplay_name());//名称  谷宇
            System.out.println(objectsDetail.getGlobal_sort());
            System.out.println(objectsDetail.getGroup_guid());
            System.out.println(objectsDetail.getOriginal_sort());//H4A编号很重要  000000000026000023000012000006
            System.out.println(objectsDetail.getNote());
            System.out.println(objectsDetail.getPerson_id());//海关员工工号 2231770
            System.out.println("&&&&&&&&&&&&&&&&");
            loginTicket.setUserGuid(objectsDetail.getUser_guid());
            loginTicket.setNickName(objectsDetail.getDisplay_name());
        }

        // 获取指定应用、指定视角的角色列表
        String roleValues = "SYSTEM_ADMIN,APP_ADMIN,LS_FT_GZ,LS_FT_EJ,LS_FT_KZ,ZN_CZ,ZN_KZ,ZN_KY,SJ_CZ,SJ_KZ,SJ_KY,SY_JS,SY_CY";
        Roles[] roles = accreditBeanReaderHelper.getBeanRoles("", AccreditCategory.Code,
                appValue,AccreditCategory.Code, //应用标识值类型
                viewValue,AccreditCategory.Code,//视角标识值类型
                RoleCategories.All,//角色标识值类型
                "");   //需要查询的属性
        for(Roles role : roles) {
            SysRole sysRole = new SysRole();
            sysRole.setRoleGuid(role.getRole_id());
            // 角色名称
            sysRole.setRoleName(role.getRole_name());
            // 权限字符
            sysRole.setRoleKey(role.getCode_name());
            // 显示顺序
            sysRole.setRoleSort(role.getSort_id());
            // 启用状态
            sysRole.setStatus(Constants.DB_IS_STATUS_NO);
            sysRole.setDelFlag(Constants.DB_IS_STATUS_NO);
            sysRole.setDeptCheckStrictly(true);
            sysRole.setMenuCheckStrictly(true);
            sysRole.setCreateTime(new Date());
            sysRole.setMenuIds(new Long[]{});
            // 校验角色名称、权限标识是否存在
            if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(sysRole))) {
                sysRole.setRoleId(roleService.selectRoleIdByRoleName(sysRole.getRoleName()));
                roleService.updateRoleInfo(sysRole);
            } else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(sysRole))) {
                sysRole.setRoleId(roleService.selectRoleIdByKeyName(sysRole.getRoleKey()));
                roleService.updateRoleInfo(sysRole);
            } else {
                roleService.insertRole(sysRole);
            }
        }
        // 获取指定用户的角色列表
        RolesOfUser[] rolesOfUser = accreditBeanReaderHelper.getBeanRolesOfUser(userValue,
                UserCategory.USER_IDENTITY, "", OrganizationCategory.NONE, appValue,
                AccreditCategory.Code,viewValue, AccreditCategory.Code, RoleCategories.All,
                DelegationCategories.All, "");//获取的属性值
        List<String> roleIds = new ArrayList<>();
        if ((null != rolesOfUser) && (rolesOfUser.length > 0)) {
            for (RolesOfUser ofUser : rolesOfUser) {
                roleIds.add(ofUser.getRole_id());
            }
        }
        // 获取指定用户的功能列表
        FunctionsOfUser[] functionsOfUsers = accreditBeanReaderHelper.getBeanFunctionsOfUser(userValue, UserCategory.USER_IDENTITY,
                "", OrganizationCategory.NONE, appValue,
                AccreditCategory.Code, viewValue, AccreditCategory.Code,
                FunctionCategories.None, DelegationCategories.All, "");
        // 获取指定应用、指定视角的角色功能关联数据。注意:需要在海关端提前预置、角色与功能按钮关联列表，同时roleValues为必填项
        FunctionsInRoles[] functionsInRoles = accreditBeanReaderHelper.getBeanFunctionsInRoles(appValue, AccreditCategory.Level, viewValue, AccreditCategory.Level, roleValues, AccreditCategory.Level, "");
        // K角色英文标识 V菜单名称集合
        /*Map<String, List<String>> hashMap = new HashMap<>();
        if ((null != functionsInRoles) && (functionsInRoles.length > 0)) {
            for (FunctionsInRoles function : functionsInRoles) {
                log.error("role_value:" + function.getRole_value());
                log.error("role_category:" + function.getRole_category());
                log.error("func_id:" + function.getFunc_id());
                log.error("app_id:" + function.getApp_id());
                log.error("parent_id:" + function.getParent_id());
                log.error("parent_code:" + function.getParent_code());
                log.error("func_name:" + function.getFunc_name());
                log.error("code_name:" + function.getCode_name());
                log.error("func_description:" + function.getFunc_description());
                log.error("sort_id:" + function.getSort_id());
                log.error("resource_level:" + function.getResource_level());
                log.error("classify:" + function.getClassify());
                log.error("object_type:" + function.getObject_type());
                log.error("hash_role:" + function.getHash_role());
                String roleValue = function.getRole_value();
                if ("2".equals(function.getClassify())){
                    if (hashMap.containsKey(function.getRole_value())) {
                        List<String> list = hashMap.get(function.getRole_value());
                        list.add(function.getFunc_name());
                        hashMap.put(roleValue,list);
                    } else {
                        List<String> list = new ArrayList<>();
                        list.add(function.getFunc_name());
                        hashMap.put(roleValue,list);
                    }
                }
            }
        }
        Set<Map.Entry<String,List<String>>> en = hashMap.entrySet();
        for (Map.Entry<String, List<String>> entry : en) {
            Long roleId = roleService.selectRoleIdByKeyName(entry.getKey());
            SysRole sysRole = roleService.selectRoleById(roleId);
            sysRole.setMenuIds(menuService.findMenuId(entry.getValue()));
            // 更新角色信息、菜单权限
            roleService.updateRole(sysRole);
        }*/
        loginTicket.setRoleIds(roleService.findRoleId(roleIds));
        String paramToken = request.getParameter(paramT);
        String token = loginService.ssoLogin(loginTicket,paramToken);
        ajax.put(Constants.TOKEN, token);
        // H4A回调成功的token
        ajax.put("paramToken", Constants.LOGIN_TOKEN_KEY + paramToken);
        return ajax;
    }

    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     * 
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
